import {
	defineStore
} from 'pinia'
import * as util from "../utils/util"
import * as API from "../api/api.js"
import {userLoginStore} from "./userLogin.js"
let plugin = requirePlugin("WechatSI");
let manager = plugin.getRecordRecognitionManager();
export const useRunInfoStore = defineStore('useRunInfo', {
	state: () => {
		return {
      totalMileage: 75,
      runAllMilleage: (0).toFixed(3),
      runMileage: (0).toFixed(3),  // 已经跑的里程（公里）
      runDuration: 0, // 已将跑的时长（分钟）
      remainingMileage: 0.000, // 剩余里程
      matchSpeed: `0'00"`,
      runType: "start",
      // latitude: 116.73201,
      // longitude: 39.558775
      centerPosition: { // 操场中心坐标
        // latitude: 39.95933,
        // longitude: 116.29845

        latitude: 39.555118272569445,
        longitude: 116.72717800564236,

        // latitude: 40.00028428819444,
        // longitude: 116.48679497612848    // 116.72717800564236      39.555118272569445
      },
      sportRange: 0,
      centerDistance: 0,
			coordinate: {
        latitude: null,
        longitude: null,
        speed: null
      },
      // polyline: {},
      proportionShow: 0.7,
      initStatus: true,
      isShowCountdown: false,
      timerNum: 0,
      totalDistance: 0,
      totalSeconds: 0,
      timer: null,
      runUuid: null,
      userInfo: null,
      timerInterval: null,
      isClickStatRun: false,
      recordEnd: false,
      showPictureUpload: false,
      importantNotice: "",
      popupExpire: "",
      bannerImg: "",
      familyBannerImg: "",
      superBannerImg: "",
      countDownTimer: null,
      countDownNum: 3,
      backgroundImg: "",
      popupUrl: "",
      isRuning: false,
      runPolyline: null,
      reportType: "day",
      superGroupDesc: null,
      familyGroupDesc: null
		}
	},
  getters: {
    // remainingMileage: (state) => {
    //   console.log("==", state.totalMileage, state.runMileage, Number(state.totalMileage) - Number(state.runMileage))
    //   return Number(state.totalMileage) - Number(state.runMileage)
    // }
  },
	actions: {
    resetAll() {
      console.log("数据重置")
      this.$reset()
      this.endTask("end")
      this.setIsRuning(false)
    },
    setInitReportType(value) {
      this.reportType = value
    },
    setPolyline(value) {
      this.runPolyline = value
    },
    setIsRuning(value) {
      this.isRuning = value
    },
    clearCountDownTimer() {
      clearInterval(this.countDownTimer)
      this.countDownTimer = null
    },
    setPictureUpload(value) {
      this.showPictureUpload = value
    },
    setImportantNotice(value) {
      this.importantNotice = value
    },
    setPopupExpire(value) {
      this.popupExpire = value
    },
    setRecordEnd(value) {
      this.recordEnd = value
    },
    setIsClickStartRun(value) {
      this.isClickStatRun = value
    },
    setTotalSeconds(value){
      this.totalSeconds = value
    },
    setCenterDistance(value) {
      this.centerDistance = value
    },
    setRunMileage(value) {
      console.log("计算后要显示的总公里====", value, Number(value).toFixed(3))
      this.runMileage = Number(value).toFixed(3)
    },
    setMatchSpeed(value) {
      this.matchSpeed = value
    },
    setRunType(value) {
      this.runType = value
    },
    setTimerNum(value) {
      this.timerNum = value
    },
    setInitStatus(value) {
      this.initStatus = value
    },
    setProportionShow(value) {
      this.proportionShow = value
    },
    handleLocation() {
      if (this.runType === "start") {
        console.log("点击开始跑步")
        this.matchSpeed = `0'00"`
        this.timerNum = "00:00"
        this.runMileage = (0).toFixed(3)
        this.runDuration = 0
        this.totalSeconds = 0
        // this.countDown().then(res => {
        //   this.getLocation()
        // })
        this.getLocation()
      }
      if (this.runType === "reStart"){
        console.log("重新开始跑步")
        this.positiveTiming()
        this.getLocation()
      }
    },
    startTask(type, isLocation) {
      this.runType = type
      const _this = this
      return new Promise((resolve, reject) => {
        this.getAuthSetting().then(() => {
          if (isLocation) {
            _this.handleLocation()
          }
          resolve()
        }).catch(err => {
          _this.getAuthorize()
          .then(() => {
            if (isLocation) {
              _this.handleLocation()
            }
            resolve()
          })
          .catch(() => {
            // 不同意给出弹框，再次确认
            _this.openConfirm()
              .then(() => {
                _this.getAuthSetting().then(() => {
                  if (isLocation) {
                    _this.handleLocation()
                  }
                  resolve()
                }).catch(err => {
                  uni.showToast({
                    title: '无法获取位置信息！无法使用位置功能',
                    icon: 'none',
                  })
                })
              })
          })
        })
      })
    },

    // 判断权限
    getAuthSetting() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success(res) {
            console.log("权限", res.authSetting)
            if(res.authSetting['scope.userLocationBackground']) {
              resolve()
            } else {
              reject()
            }
          }
        })
      })
    },

    // 初次位置授权
    getAuthorize(){
      return new Promise((resolve, reject) => {
        uni.authorize({
          scope: 'scope.userLocationBackground',
          success: () => {
            // this.initStatus = false
            console.log("允许授权后台")
            resolve() // 允许授权
          },
          fail: () => {
            this.initStatus = true
            console.log("拒绝授权")
            reject() // 拒绝授权
          },
        })
      })
    },
    // 用户首次拒绝授权后(考虑是误点击)，弹框提示是否手动打开位置授权
    openConfirm(){
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: '请求授权当前位置',
          content: '我们需要获取地理位置信息',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.openSetting({
                success(res) {
                  resolve() // 打开地图权限设置
                }
              })
            } else if (res.cancel) {
              reject()
            }
          },
        })
      })
    },

    offLocationChangeFn() {
      uni.offLocationChange()
    },

    locationChangeFn(data){
      console.log("字符串data", JSON.stringify(data))
      console.log("当前经纬度", data)
      let dataCopy = JSON.parse(JSON.stringify(data))
      let latitude = Number(data.latitude).toFixed(7)
      let longitude = Number(data.longitude).toFixed(7)
      this.coordinate = {
        latitude: latitude,
        longitude: longitude,
        speed: data.speed,
        accuracy: data.accuracy
      }
    },

    getLocation(id) {
      console.log("开始获取位置")
      // this.polyline = {}
      // 39.95933 116.29845 40.000308973524305 116.48688883463542
      // wgs84
      // 当前位置的经度：116.4807217738034
      // 当前位置的纬度：39.99899420530856
      // uni.getLocation({
      //   type: 'gcj02', // wgs84
      //   success: function (res) {
      //     console.log('当前位置的经度：' + res.longitude);
      //     console.log('当前位置的纬度：' + res.latitude);
      //   }
      // });
      uni.startLocationUpdateBackground({
        type: 'gcj02', // gcj02
        success: (res) => {
          console.log("开启前后台定位", res, this.runType)
          this.isRuning = true
          this.initStatus = false
          console.log("runType===0", this.runType)
          if (this.runType === "start") {
            this.countDown().then(res => {
              uni.onLocationChange((data) => {
                this.locationChangeFn(data)
                // let dataCopy = JSON.parse(JSON.stringify(data))
                // let latitude = Number(data.latitude).toFixed(7)
                // let longitude = Number(data.longitude).toFixed(7)
                // this.coordinate = {
                //   latitude: latitude,
                //   longitude: longitude,
                //   speed: data.speed
                // }
              });
            })
          }

          console.log("runType===1", this.runType)
          if (this.runType === "reStart"){
            uni.onLocationChange((data) => {
              console.log("字符串data---restart", JSON.stringify(data))
              console.log("当前经纬度=========实时定位-restart", data)
              this.locationChangeFn(data)
              // let latitude = Number(data.latitude).toFixed(7)
              // let longitude = Number(data.longitude).toFixed(7)
              // this.coordinate = {
              //   latitude: latitude,
              //   longitude: longitude,
              //   speed: data.speed
              // }
            });
          }
        },
        fail: error => {
          console.log(error)
          this.initStatus = true
          this.proportionShow = 0.7
          uni.showToast({
            title: '无法获取位置信息！无法使用位置功能',
            icon: 'none',
          })
        }
      });

      // 实时定位监听失败处理
      uni.onLocationChangeError((res) => {
        uni.showToast({
          title: "你的信号较弱～",
          icon: "none",
        })
        this.onBurialWeakNetworkInfo()
      })
    },

    onBurialWeakNetworkInfo() {
      uni.getSystemInfo({
        success: (res) => {
          let params = {
            userId: this.userInfo?.customers?.customerId,
            brand: res.brand,
            model: res.model,
            wechatVersion: res.version,
            systemVersion: res.system,
            sdkVersion: res.SDKVersion
          }
          API.burialWeakNetworkInfo(params).then(res => {
            if (res.code === 0) {
              console.log("弱网埋点成功")
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },

    endTask(type) {
      return new Promise((resolve, reject) => {
        console.log("结束定位", type)
        this.runType = type
        clearInterval(this.timer)
        this.offLocationChangeFn()
        // clearInterval(this.timerInterval)
        uni.stopLocationUpdate({
          success: function(){
            console.log("结束定位成功")
          },
          fail: function(){
            console.log("结束定位失败")
          }
        })
        uni.removeStorageSync("prePosition")
        resolve()
      })
    },

    // 6秒倒计时
    countDown() {
      return new Promise((resolve, reject) => {
        this.isShowCountdown = true
        this.proportionShow = 0.35
        this.initStatus = false
        // setTimeout(() => {
        //   this.isShowCountdown = false
        //   this.positiveTiming()
        //   resolve()
        // }, 6200);
        this.startAnimationTimer().then(res => {
          this.isShowCountdown = false
          this.positiveTiming()
          this.isClickStatRun = true
          resolve()
        })
      })
    },

    //开启动画定时器
    startAnimationTimer(){
      return new Promise((resolve, reject) => {
        if (this.countDownTimer) {
          return
        }
        //标记开启动画
        this.isShowCountdown = true
        //开启定时
        this.countDownTimer = setInterval(() => {
          this.countDownNum--
          if (this.countDownNum <= 0) {
            //关闭定时器
            clearInterval(this.countDownTimer)
            this.countDownTimer = null
            //关闭之后恢复数字
            setTimeout(() => {
              this.countDownNum = 3
            }, 1000)
            //关闭弹窗(1s之后关闭,让GO!显示出来再关闭)
            setTimeout(() => {
              //关闭动画
              resolve()
            }, 1000)
          }
          // this.speechSynthesis()
        }, 1000)
      })
    },

    // 语音播报
    speechSynthesis() {
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: String(this.countDownNum+1),
        success: function(res) {
          let music = null;
          music = uni.createInnerAudioContext(); //创建播放器对象
          console.log("语音播报", res.filename)
          music.src = res.filename;
          music.play(); //执行播放
          music.onEnded(() => {
            //播放结束
            music = null;
          });
        },
        fail: function(err) {
          console.log("语音播放失败", err)
        }
      })
    },

    // 配速
    handleSpeed() {
      console.log("配速计算前的距离", this.runMileage)
      if (this.runMileage > 0.01) {
        let runDuration = (Number(this.totalSeconds)/60).toFixed(2) // 分钟
        let matchSpeed = (Number(runDuration)/Number(this.runMileage)).toFixed(2)
        let matchSpeedObj = util.timeConvert(matchSpeed)
        this.matchSpeed = `${matchSpeedObj.min}'${matchSpeedObj.sen}"`
        console.log("配速", this.matchSpeed)
      }
    },

    // 计时器
    positiveTiming() {
      console.log("计时器开始")
      this.isShowCountdown = false
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.totalSeconds++
        this.timerNum = util.getTime(this.totalSeconds) || "00:00"
        this.handleSpeed()
        console.log("this.totalSeconds-计时器", this.totalSeconds, this.timerNum)
      }, 1000);
    },

    // 停止计时
    stopCountDown() {
      clearInterval(this.timer)
    },

    // 进行经纬度转换为距离的计算
    Rad(d) {
      return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
    },
    // 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度  默认单位km
    getMapDistance(lat1, lng1, lat2, lng2) {
      console.log("两个坐标", lat1, lng1, lat2, lng2 )
      var radLat1 = this.Rad(lat1);
      var radLat2 = this.Rad(lat2);
      var a = radLat1 - radLat2;
      var b = this.Rad(lng1) - this.Rad(lng2);
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000; //输出为公里
      // s = s.toFixed(2);
      console.log("计算的一小段距离公里", s)
      return s
    },

    // 开始跑步
    onStartRun() {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      const userLoginData = userLoginStore()
      return new Promise((resolve, reject) => {
        API.createMileage({userId: this.userInfo?.customers?.customerId, loginMobile: this.userInfo?.mobile, loginType: userLoginData.loginType}).then(res => {
          if (res.code === 0) {
            this.runUuid = res.data
            resolve(res)
          } else {
            uni.showToast({
              title: res.message || "开始跑步失败",
              icon: "none"
            })
            reject()
          }
        }).catch(err => {
          console.log(err)
          uni.showToast({
            title: err.message || "开始跑步失败",
            icon: "none"
          })
          reject()
        })
      })
    },

    // 里程结束
    onEndMileage(duration, distance) {
      let params = {
        userId: this.userInfo.customers.customerId,
        uuid: this.runUuid,
        duration,
        distance
      }
      return API.endMileage(params).then(res => {
        if (res.code === 0) {
          this.recordEnd = true
        }
      }).catch(err => {
        console.log(err)
        uni.showToast({
          title: err.message || "里程结束",
          icon: "none"
        })
      })
    },

    // 更新里程
    onUpdateMileage(duration, distance, intervalDistance, intervalDuration, latitude, longitude, speed, accuracy) {
      let params = {
        userId: this.userInfo?.customers?.customerId,
        uuid: this.runUuid,
        duration,
        distance,
        intervalDistance,
        intervalDuration,
        latitude,
        longitude,
        speed,
        accuracy
      }
      return API.updateMileage(params).then(res => {
        if (res.code === 0) {

        }
      }).catch(err => {
        console.log(err)
        uni.showToast({
          title: err.message || "里程更新失败",
          icon: "none"
        })
      })
    },
    // 里程统计
    onListMileage() {
      this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
      console.log("里程统计", this.userInfo)
      return API.listMileage({userId: this.userInfo.customers.customerId}).then(res => {
        if (res.code === 0) {
          this.runAllMilleage = Number(res.data.distanceTotal).toFixed(3)
          this.onRemainingMileage()
          return {
            distanceTotal: this.runAllMilleage,
            durationTotal: Number(res.data.durationTotal),
            list: res.data.mileages
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },

    // 运动话术建议
    onGetSportsAdvise() {
      return new Promise((resolve, reject) => {
        API.getChatAdvice({userId: this.userInfo.customers.customerId}).then(res => {
          if (res.code === 0) {
            resolve(res)
          } else {
            reject()
          }
        }).catch(err => {
          console.log(err)
          reject()
        })
      })
    },

    onRemainingMileage() {
      if (Number(this.totalMileage) >= Number(this.runAllMilleage)) {
        this.remainingMileage =  (Number(this.totalMileage) - Number(this.runAllMilleage)).toFixed(3)
      }
    },
    getConfigList() {
      let params = {
        "configKeys": [
          "centor_point_latitude",
          "centor_point_longitude",
          "sport_range",
          "homepage_popup_img",
          "homepage_popup_img_expire",
          "run_group_banner_img",
          "homepage_background_img",
          "homepage_popup_skip_url",
          "run_group_banner_img_super",
          "run_group_banner_img_family",
          "super_run_group_event_desc",
          "family_run_group_event_desc"
        ]
      }
      return API.getConfigList(params).then(res => {
        if (res.code === 0) {
          res.data.forEach(item => {
            if (item.configKey === "centor_point_latitude"){
              this.centerPosition.latitude = item.configValue
            }
            if (item.configKey === "centor_point_longitude"){
              this.centerPosition.longitude = item.configValue
            }
            if (item.configKey === "sport_range"){
              this.sportRange = item.configValue
            }
            if (item.configKey === "homepage_popup_img") {
							this.importantNotice = item.configValue
            }
            if (item.configKey === "homepage_popup_img_expire") {
              this.popupExpire = item.configValue
            }
            if (item.configKey === "run_group_banner_img") {
              this.bannerImg = item.configValue
            }
            if (item.configKey === "homepage_background_img") {
              this.backgroundImg = item.configValue
            }
            if (item.configKey === "homepage_popup_skip_url") {
              this.popupUrl = item.configValue
            }
            if (item.configKey === "run_group_banner_img_super") {
              this.superBannerImg = item.configValue
            }
            if (item.configKey === "run_group_banner_img_family") {
              this.familyBannerImg = item.configValue
            }
            if (item.configKey === "super_run_group_event_desc") {
              this.superGroupDesc = item.configValue
            }
            if (item.configKey === "family_run_group_event_desc") {
              this.familyGroupDesc = item.configValue
            }
          })
        }
      }).catch(err => {

      })
    }
  }
})

